package com.bub.pay.framework.common.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Base64Utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class EncryptionUtil {

    public final static String md5withRSA = "MD5withRSA";

    public final static String SHA1withRSA = "SHA1withRSA";

    public static PasswordEncoder encode() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    public static boolean matches(CharSequence rawPassword, String encodedPassword) {
        boolean flag = false;
        try {
            flag = EncryptionUtil.encode().matches(rawPassword, encodedPassword);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return flag;
    }

    public static class AES {
        private static final String KEY_ALGORITHM = "AES";
        private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法

        public static String encrypt(String content, String password) throws Exception {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return Base64.encodeBase64String(result);//通过Base64转码返回
        }

        public static String encrypt(String content, Key key) throws Exception {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return Base64.encodeBase64String(result);//通过Base64转码返回
        }

        public static String decrypt(String content, String password) throws Exception {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
            //执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));
            return new String(result, "utf-8");
        }

        public static String decrypt(String content, Key key) throws Exception {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, key);
            //执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));
            return new String(result, "utf-8");
        }

        private static SecretKeySpec getSecretKey(final String password) throws Exception {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            //AES 要求密钥长度为 128
            kg.init(128, secureRandom);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
        }
    }

    public static class RSA {

        /**
         * RSA最大加密明文大小
         */
        private static final int MAX_ENCRYPT_BLOCK = 117;

        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 128;

        /**
         * 加密
         *
         * @param content 加密内容
         * @param key     key
         * @return 加密结果
         */
        public static byte[] encrypt(byte[] content, Key key) throws NoSuchAlgorithmException, IllegalBlockSizeException, IOException, InvalidKeyException, BadPaddingException {
            try {
                // 初始化参数
                Cipher cipher = Cipher.getInstance("RSA");

                cipher.init(Cipher.ENCRYPT_MODE, key);

                // 对数据进行分断加密
                int length = content.length;
                try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    for (int offSet = 0; offSet < length; offSet += MAX_ENCRYPT_BLOCK) {
                        out.write(cipher.doFinal(content, offSet, Math.min(MAX_ENCRYPT_BLOCK, length - offSet)));
                    }
                    return Base64Utils.encode(out.toByteArray());
                }
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 加密
         *
         * @param content 加密内容
         * @param key     key
         * @return 加密结果
         */
        public static String encrypt(String content, Key key) throws NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
            return new String(encrypt(content.getBytes("UTF-8"), key), "UTF-8");
        }

        public static String encryptByPrivateKey2HexString(String content, String privatekey) {
            try {
                PrivateKey privateKey = RsaKeyHelper.parsePrivateKey(privatekey);
                return new String(Hex.encode(encryptNative(content.getBytes("UTF-8"), privateKey)));
            } catch (Exception e) {
                throw new RuntimeException("私钥加密错误");
            }
        }

        /**
         * 通过公钥加密
         *
         * @param content      加密内容
         * @param publicKeyStr 公钥
         * @return 加密结果
         */
        public static String encryptByPublicKey(String content, String publicKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
            PublicKey publicKey = parsePublicKey(publicKeyStr);
            return encrypt(content, publicKey);
        }

        public static String encryptByPub2HexString(String content, String publicKeyStr) {
            PublicKey publicKey;
            try {
                publicKey = RsaKeyHelper.parsePublicKey(publicKeyStr);
            } catch (Exception e) {
                throw new RuntimeException("公钥错误");
            }

            try {
                return new String(Hex.encode(encryptNative(content.getBytes("UTF-8"), publicKey)));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("加密时编码失败");
            }
        }

        public static byte[] encryptNative(byte[] content, Key key) {
            try {
                // 初始化参数
                Cipher cipher = Cipher.getInstance("RSA");

                cipher.init(Cipher.ENCRYPT_MODE, key);

                // 对数据进行分断加密
                int length = content.length;
                try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    for (int offSet = 0; offSet < length; offSet += MAX_ENCRYPT_BLOCK) {
                        out.write(cipher.doFinal(content, offSet, Math.min(MAX_ENCRYPT_BLOCK, length - offSet)));
                    }
                    return out.toByteArray();
                }
            } catch (Exception e) {
                throw new RuntimeException("加密失败");
            }
        }

        /**
         * 解密
         *
         * @param content 解密内容
         * @param key     key
         * @return 解密结果
         */
        public static byte[] decrypt(byte[] content, Key key) throws NoSuchAlgorithmException, IllegalBlockSizeException, IOException, InvalidKeyException, BadPaddingException {
            try {
                // 初始化参数
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.DECRYPT_MODE, key);

                content = Base64Utils.decode(content);
                // 对数据进行分断加密
                int length = content.length;
                try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    for (int offSet = 0; offSet < length; offSet += MAX_DECRYPT_BLOCK) {
                        out.write(cipher.doFinal(content, offSet, Math.min(MAX_DECRYPT_BLOCK, length - offSet)));
                    }
                    return out.toByteArray();
                }
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }


        public static byte[] decryptNative(byte[] content, Key key) throws NoSuchAlgorithmException, IllegalBlockSizeException, IOException, InvalidKeyException, BadPaddingException {
            try {
                // 初始化参数
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.DECRYPT_MODE, key);

                // 对数据进行分断加密
                int length = content.length;
                try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    for (int offSet = 0; offSet < length; offSet += MAX_DECRYPT_BLOCK) {
                        out.write(cipher.doFinal(content, offSet, Math.min(MAX_DECRYPT_BLOCK, length - offSet)));
                    }
                    return out.toByteArray();
                }
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 解密
         *
         * @param content 解密内容
         * @param key     key
         * @return 解密结果
         */
        public static String decrypt(String content, Key key) throws NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
            return new String(decrypt(content.getBytes("UTF-8"), key), "UTF-8");
        }

        /**
         * 通过公钥解密
         *
         * @param content      解密内容
         * @param publicKeyStr 公钥
         * @return 解密结果
         */
        public static String decryptByPublicKey(String content, String publicKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
            PublicKey publicKey = parsePublicKey(publicKeyStr);
            return decrypt(content, publicKey);
        }

        public static String decryptByHexString(String content, String publicKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
            PublicKey publicKey = parsePublicKey(publicKeyStr);
            return new String(decryptNative(Hex.decode(content), publicKey));
        }

        public static byte[] decryptByHexStringNative(String content, String publicKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
            PublicKey publicKey = parsePublicKey(publicKeyStr);
            return decryptNative(Hex.decode(content), publicKey);
        }

        /**
         * 通过私钥解密
         *
         * @param content       解密内容
         * @param privateKeyStr 私钥
         * @return 解密结果
         */
        public static String decryptByPrivateKey(String content, String privateKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
            PrivateKey privateKey = parsePrivateKey(privateKeyStr);
            return decrypt(content, privateKey);
        }

        /**
         * RSA公钥转换
         *
         * @param publicKeyStr 公钥字符串
         * @return 公钥
         * @throws InvalidKeySpecException
         */
        public static PublicKey parsePublicKey(String publicKeyStr) throws InvalidKeySpecException {
            PublicKey publicKey = null;
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                byte[] encodedKey = Base64Utils.decodeFromString(publicKeyStr);
                publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            } catch (NoSuchAlgorithmException e) {
            }
            return publicKey;
        }

        /**
         * RSA私钥转换
         *
         * @param privateKeyStr 私钥字符串
         * @return 私钥
         * @throws InvalidKeySpecException
         */
        public static PrivateKey parsePrivateKey(String privateKeyStr) throws InvalidKeySpecException {
            PrivateKey privateKey = null;
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                byte[] encodedKey = Base64Utils.decodeFromString(privateKeyStr);
                privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
            } catch (NoSuchAlgorithmException e) {
            }
            return privateKey;
        }

        /**
         * 签名
         *
         * @param data          待签名数据
         * @param dataCharset   待签名数据转字节流字符编码
         * @param privateKey    私钥
         * @param signAlgorithm 签名算法
         * @return 签名
         */
        public static String sign(String data, String dataCharset, String privateKey, String signAlgorithm) throws Exception {

            PrivateKey key = RsaKeyHelper.parsePrivateKey(privateKey);
            Signature signature = Signature.getInstance(signAlgorithm);
            signature.initSign(key);
            signature.update(data.getBytes(dataCharset));
            return new String(Base64.encodeBase64(signature.sign()));
        }

        /**
         * 验签
         *
         * @param srcData   原始字符串
         * @param publicKey 公钥
         * @param sign      签名
         * @return 是否验签通过
         */
        public static boolean verify(String srcData, String srcDataCharset, String publicKey, String sign, String signCharset, String signAlgorithm) throws Exception {

            PublicKey key = RsaKeyHelper.parsePublicKey(publicKey);
            Signature signature = Signature.getInstance(signAlgorithm);
            signature.initVerify(key);
            signature.update(srcData.getBytes(srcDataCharset));
            return signature.verify(Base64.decodeBase64(sign.getBytes(signCharset)));
        }

    }


    public static class DES3 {

        private static final String Algorithm = "DESede"; // 定义 加密算法,可用

        // / <summary>
        // / 3des加密
        // / </summary>
        // / <param name="value">待加密字符串</param>
        // / <param name="strKey">原始密钥字符串</param>
        // / <returns></returns>
        public static String encrypt3DES(String value, String key) throws Exception {
            String str = Base64.encodeBase64String(encryptMode(key.getBytes(), value.getBytes("UTF-8")));
            return str;
        }

        public static String decrypt3DES(String value, String key) throws Exception {
            return new String(decryptMode(key.getBytes(), Base64.decodeBase64(value)), "UTF-8");
        }

        //加密
        // keybyte为加密密钥，长度为24字节
        // src为被加密的数据缓冲区（源）
        public static byte[] encryptMode(byte[] keybyte, byte[] src) {
            try {
                // 生成密钥
                SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密
                Cipher c1 = Cipher.getInstance(Algorithm);
                c1.init(Cipher.ENCRYPT_MODE, deskey);
                return c1.doFinal(src);
            } catch (java.security.NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            } catch (javax.crypto.NoSuchPaddingException e2) {
                e2.printStackTrace();
            } catch (java.lang.Exception e3) {
                e3.printStackTrace();
            }
            return null;
        }


        // 解密
        // keybyte为解密密钥，长度为24字节
        // src为被加密的数据缓冲区（源）
        public static byte[] decryptMode(byte[] keybyte, byte[] src) {
            try {
                // 生成密钥
                SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密
                Cipher c1 = Cipher.getInstance(Algorithm);
                c1.init(Cipher.DECRYPT_MODE, deskey);
                return c1.doFinal(src);
            } catch (java.security.NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            } catch (javax.crypto.NoSuchPaddingException e2) {
                e2.printStackTrace();
            } catch (java.lang.Exception e3) {
                e3.printStackTrace();
            }
            return null;
        }

    }


}
